<template>
  <div class="forum-container">
    <!-- 顶部操作栏 -->
    <el-card class="operation-bar">
      <div class="header-container">
        <div class="left-section">
          <el-radio-group v-model="currentTab" @change="handleTabChange">
            <el-radio-button label="all">全部</el-radio-button>
            <el-radio-button label="experience">经验分享</el-radio-button>
            <el-radio-button label="question">问题解答</el-radio-button>
            <el-radio-button label="discussion">讨论交流</el-radio-button>
          </el-radio-group>
        </div>
        <div class="right-section">
          <el-button type="primary" @click="showPostDialog">发布新帖子</el-button>
        </div>
      </div>
    </el-card>

    <!-- 帖子列表 -->
    <el-card class="post-list">
      <el-table :data="postList" v-loading="loading">
        <el-table-column prop="title" label="标题" min-width="200">
          <template slot-scope="scope">
            <el-link type="primary" @click="viewPost(scope.row)">{{ scope.row.title }}</el-link>
          </template>
        </el-table-column>
        <el-table-column prop="type" label="类型" width="100">
          <template slot-scope="scope">
            {{ getPostType(scope.row.type) }}
          </template>
        </el-table-column>
        <el-table-column prop="author" label="作者" width="120"></el-table-column>
        <el-table-column prop="createTime" label="发布时间" width="160">
          <template slot-scope="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="replyCount" label="回复数" width="80"></el-table-column>
        <el-table-column label="操作" width="280">
          <template slot-scope="scope">
            <el-button 
              type="text" 
              @click="viewPost(scope.row)"
            >查看帖子</el-button>
                <!-- <el-button 
                type="text" 
                @click="viewReplies(scope.row)"
                >查看回复</el-button>
                <el-button 
                type="text" 
                @click="showReplyDialog(scope.row)"
                >回复</el-button> -->
            <el-button 
              type="text" 
              @click="editPost(scope.row)" 
              v-if="scope.row.author === username"
            >编辑</el-button>
            <el-button 
              type="text" 
              @click="deletePost(scope.row.id)" 
              v-if="scope.row.author === username"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          @current-change="handlePageChange"
          :current-page="currentPage"
          :page-size="pageSize"
          :total="total"
          layout="total, prev, pager, next"
        >
        </el-pagination>
      </div>
    </el-card>

    <!-- 发布/编辑帖子对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="postDialogVisible" width="60%">
      <el-form :model="postForm" :rules="rules" ref="postForm" label-width="80px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="postForm.title" placeholder="请输入标题"></el-input>
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="postForm.type" placeholder="请选择帖子类型">
            <el-option label="经验分享" value="experience"></el-option>
            <el-option label="问题解答" value="question"></el-option>
            <el-option label="讨论交流" value="discussion"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input type="textarea" v-model="postForm.content" rows="6"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="postDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitPost">发布</el-button>
      </div>
    </el-dialog>

    <!-- 帖子详情对话框 -->
    <el-dialog title="帖子详情" :visible.sync="detailDialogVisible" width="70%">
      <div v-if="currentPost" class="post-detail">
        <!-- 帖子内容部分 -->
        <div class="post-main">
          <h2>{{ currentPost.title }}</h2>
          <div class="post-info">
            <span>作者：{{ currentPost.author }}</span>
            <span>发布时间：{{ formatDate(currentPost.createTime) }}</span>
            <span>类型：{{ getPostType(currentPost.type) }}</span>
          </div>
          <div class="post-content">{{ currentPost.content }}</div>
        </div>

        <!-- 回复区域 -->
        <div class="reply-section">
          <!-- 快速回复框 -->
          <div class="quick-reply">
            <h3>发表回复</h3>
            <el-form :model="replyForm" :rules="replyRules" ref="quickReplyForm">
              <el-form-item prop="content">
                <el-input
                  type="textarea"
                  v-model="replyForm.content"
                  rows="3"
                  placeholder="写下你的回复..."
                ></el-input>
              </el-form-item>
              <div class="reply-actions">
                <el-button type="primary" @click="submitQuickReply">发表回复</el-button>
              </div>
            </el-form>
          </div>

          <!-- 回复列表 -->
          <div class="reply-list">
            <h3>全部回复 ({{ replyList.length }})</h3>
            <div v-if="replyList.length === 0" class="no-reply">
              暂无回复，来说第一句吧
            </div>
            <div v-else>
              <div v-for="reply in replyList" :key="reply.id" class="reply-item">
                <div class="reply-info">
                  <span class="reply-author">{{ reply.author }}</span>
                  <span class="reply-time">{{ formatDate(reply.createTime) }}</span>
                </div>
                <div class="reply-content">{{ reply.content }}</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 添加回复对话框 -->
    <el-dialog title="发表回复" :visible.sync="replyDialogVisible" width="50%">
      <el-form :model="replyForm" :rules="replyRules" ref="replyForm">
        <el-form-item prop="content">
          <el-input
            type="textarea"
            v-model="replyForm.content"
            :rows="4"
            placeholder="请输入回复内容..."
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="replyDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitReply">发表回复</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'ForumList',
  data() {
    return {
      loading: false,
      currentTab: 'all',
      postList: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      
      // 发布帖子相关
      postDialogVisible: false,
      dialogTitle: '发布新帖子',
      postForm: {
        title: '',
        type: '',
        content: ''
      },
      rules: {
        title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
        type: [{ required: true, message: '请选择类型', trigger: 'change' }],
        content: [{ required: true, message: '请输入内容', trigger: 'blur' }]
      },
      
      // 帖子详情相关
      detailDialogVisible: false,
      currentPost: null,
      replyList: [],
      replyContent: '',
      
      // 用户信息
      username: localStorage.getItem('username'),
      
      // 添加回复相关数据
      replyDialogVisible: false,
      replyForm: {
        content: '',
        postId: null
      },
      replyRules: {
        content: [
          { required: true, message: '请输入回复内容', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 获取帖子列表
    async fetchPosts() {
      try {
        this.loading = true
        const response = await this.$axios.get('/forum/list', {
          params: {
            type: this.currentTab === 'all' ? '' : this.currentTab,
            page: this.currentPage,
            size: this.pageSize
          }
        })
        
        if (response.data.code === 200) {
          const pageResult = response.data.data
          this.postList = pageResult.records
          this.total = pageResult.total
        }
      } catch (error) {
        this.$message.error('获取帖子列表失败')
      } finally {
        this.loading = false
      }
    },

    // 发布新帖子
    async submitPost() {
      try {
        const valid = await this.$refs.postForm.validate()
        if (valid) {
          const url = this.postForm.id ? '/forum/edit' : '/forum/add'
          await this.$axios.post(url, {
            ...this.postForm,
            author: this.username
          })
          
          this.$message.success(this.postForm.id ? '修改成功' : '发布成功')
          this.postDialogVisible = false
          this.fetchPosts()
        }
      } catch (error) {
        this.$message.error('操作失败：' + error.message)
      }
    },

    // 查看帖子详情
    async viewPost(post) {
      try {
        // 1. 获取帖子详情
        const postResponse = await this.$axios.get(`/forum/${post.id}`)
        if (postResponse.data.code === 200) {
          this.currentPost = postResponse.data.data
          
          // 2. 获取回复列表
          const replyResponse = await this.$axios.get(`/forum/reply/list/${post.id}`)
          if (replyResponse.data.code === 200) {
            this.replyList = replyResponse.data.data.records || []
          }
          
          this.detailDialogVisible = true
        }
      } catch (error) {
        this.$message.error('获取帖子详情失败')
      }
    },

    // 发表回复
    async submitReply() {
      try {
        const valid = await this.$refs.replyForm.validate()
        if (valid) {
          const response = await this.$axios.post('/forum/reply/add', {
            postId: this.replyForm.postId,
            content: this.replyForm.content,
            author: this.username
          })
          
          if (response.data.code === 200) {
            this.$message.success('回复成功')
            this.replyDialogVisible = false
            this.replyForm.content = ''
            // 刷新帖子列表以更新回复数
            this.fetchPosts()
          } else {
            this.$message.error(response.data.msg || '回复失败')
          }
        }
      } catch (error) {
        this.$message.error('回复失败：' + error.message)
      }
    },

    // 删除帖子
    async deletePost(id) {
      try {
        await this.$confirm('确定要删除这个帖子吗？', '提示', {
          type: 'warning'
        })
        
        await this.$axios.delete(`/forum/${id}`)
        this.$message.success('删除成功')
        this.fetchPosts()
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('删除失败')
        }
      }
    },

    // 编辑帖子
    editPost(post) {
      this.dialogTitle = '编辑帖子'
      this.postForm = { ...post }
      this.postDialogVisible = true
    },

    // 工具方法
    getPostType(type) {
      const types = {
        experience: '经验分享',
        question: '问题解答',
        discussion: '讨论交流'
      }
      return types[type] || type
    },

    formatDate(dateStr) {
      if (!dateStr) return ''
      const date = new Date(dateStr)
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
    },

    // 事件处理
    handleTabChange() {
      this.currentPage = 1
      this.fetchPosts()
    },

    handlePageChange(page) {
      this.currentPage = page
      this.fetchPosts()
    },

    showPostDialog() {
      this.dialogTitle = '发布新帖子'
      this.postForm = {
        title: '',
        type: '',
        content: ''
      }
      this.postDialogVisible = true
    },

    // 显示回复对话框
    showReplyDialog(post) {
      this.replyForm.postId = post.id
      this.replyDialogVisible = true
    },

    // 查看回复列表
    async viewReplies(post) {
      try {
        const response = await this.$axios.get(`/forum/reply/list/${post.id}`)
        if (response.data.code === 200) {
          this.replyList = response.data.data.records || []
          this.$msgbox({
            title: '回复列表',
            message: h => {
              return (
                <div class="reply-list-dialog">
                  <div class="reply-header">
                    <div class="post-title">《{post.title}》的回复列表</div>
                    <div class="reply-count">共 {this.replyList.length} 条回复</div>
                  </div>
                  
                  {this.replyList.length === 0 ? (
                    <div class="no-reply">
                      <i class="el-icon-chat-dot-square"></i>
                      <p>暂无回复，快来说第一句吧~</p>
                    </div>
                  ) : (
                    <div class="reply-items">
                      {this.replyList.map(reply => (
                        <div class="reply-item" key={reply.id}>
                          <div class="reply-item-header">
                            <div class="reply-user">
                              <i class="el-icon-user"></i>
                              <span class="reply-author">{reply.author}</span>
                            </div>
                            <div class="reply-meta">
                              <i class="el-icon-time"></i>
                              <span class="reply-time">{this.formatDate(reply.createTime)}</span>
                              <span class="reply-floor">#{reply.id}</span>
                            </div>
                          </div>
                          <div class="reply-content">
                            <i class="el-icon-chat-line-round"></i>
                            {reply.content}
                          </div>
                        </div>
                      ))}
                    </div>
                  )}
                </div>
              )
            },
            showCancelButton: false,
            showConfirmButton: true,
            confirmButtonText: '关闭',
            customClass: 'reply-list-msgbox'
          })
        }
      } catch (error) {
        this.$message.error('获取回复列表失败')
      }
    },

    // 修改 submitQuickReply 方法（用于帖子详情中的快速回复）
    async submitQuickReply() {
      try {
        const valid = await this.$refs.quickReplyForm.validate()
        if (valid) {
          const response = await this.$axios.post('/forum/reply/add', {
            postId: this.currentPost.id,
            content: this.replyForm.content,
            author: this.username
          })
          
          if (response.data.code === 200) {
            this.$message.success('回复成功')
            this.replyForm.content = ''
            
            // 重新获取回复列表
            const replyResponse = await this.$axios.get(`/forum/reply/list/${this.currentPost.id}`)
            if (replyResponse.data.code === 200) {
              this.replyList = replyResponse.data.data.records || []
            }
          } else {
            this.$message.error(response.data.msg || '回复失败')
          }
        }
      } catch (error) {
        this.$message.error('回复失败：' + error.message)
      }
    }
  },
  created() {
    this.fetchPosts()
  }
}
</script>

<style>
.forum-container {
  padding: 20px;
}

.operation-bar {
  margin-bottom: 20px;
}

.header-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 10px;
}

.post-list {
  margin-bottom: 20px;
}

/* 添加到已有的 style 标签中，注意移除 scoped 属性以使样式对话框生效 */
.reply-list-dialog {
  max-height: 600px;
  overflow-y: auto;
  padding: 20px;
  background: #f9fafc;
}

.reply-header {
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 2px solid #409EFF;
}

.reply-header .post-title {
  font-size: 18px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 8px;
}

.reply-header .reply-count {
  font-size: 14px;
  color: #909399;
}

.no-reply {
  text-align: center;
  padding: 40px 0;
  color: #909399;
}

.no-reply i {
  font-size: 48px;
  margin-bottom: 10px;
  color: #c0c4cc;
}

.no-reply p {
  font-size: 16px;
  margin: 0;
}

.reply-items {
  padding: 10px 0;
}

.reply-item {
  background: white;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 16px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  transition: all 0.3s;
}

.reply-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.1);
}

.reply-item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.reply-user {
  display: flex;
  align-items: center;
}

.reply-user i {
  color: #409EFF;
  margin-right: 8px;
  font-size: 16px;
}

.reply-author {
  font-weight: bold;
  color: #409EFF;
  font-size: 15px;
}

.reply-meta {
  display: flex;
  align-items: center;
  color: #909399;
  font-size: 13px;
}

.reply-meta i {
  margin-right: 4px;
}

.reply-time {
  margin-right: 12px;
}

.reply-floor {
  color: #409EFF;
  font-weight: bold;
}

.reply-content {
  position: relative;
  padding: 12px 16px;
  background: #f5f7fa;
  border-radius: 4px;
  color: #606266;
  line-height: 1.6;
}

.reply-content i {
  position: absolute;
  left: -22px;
  top: 14px;
  color: #409EFF;
}

.reply-list-msgbox {
  width: 700px !important;
}

.reply-list-msgbox .el-message-box__header {
  padding: 15px 20px;
  background: #409EFF;
}

.reply-list-msgbox .el-message-box__title {
  color: white;
}

.reply-list-msgbox .el-message-box__headerbtn .el-message-box__close {
  color: white;
}

.reply-list-msgbox .el-message-box__content {
  padding: 0;
}

.reply-list-msgbox .el-message-box__btns {
  padding: 15px 20px;
  border-top: 1px solid #ebeef5;
}
</style> 